package cn.springcloud.fix.oauth.starter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 替换掉 ExceptionTranslationFilter 的 authenticationEntryPoint，默认是 OAuth2AuthenticationEntryPoint
 * 携带token会进入 OAuth2AuthenticationProcessingFilter
 * 不携带token或者token过期会进入这里
 */
@Slf4j
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException {
		log.error(e.getMessage(), e);

		Throwable cause = e.getCause();
		response.setStatus(HttpStatus.OK.value());
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("status", 403);
		if (cause instanceof InvalidTokenException) {
			resultMap.put("message", "认证失败,无效或过期token");
		} else {
			resultMap.put("message", "认证失败,没有携带token");
		}
		PrintWriter out = response.getWriter();
		out.print(JSON.toJSONString(resultMap));
		out.flush();
		out.close();
	}
}
